#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2014-08-22 01:14:23
# @Author  : shitao.tommy (hero007asd@gmail.com)
# @Link    : http://example.org
# @Version : $Id$

from framework.db.basedb import BaseDb
from tornado import gen
from lib import log,libtime


class Accident(BaseDb):

    @gen.coroutine
    def new(self, student_id, acc_info):
        '''发布特殊事件'''
        resp = ''
        ins_sql = '''INSERT INTO tp_dorm_accident(Faccident_info,Fstudent_id,Fcreate_time)
                    VALUES(%s,%s,UNIX_TIMESTAMP())'''
        try:
            ret = yield self.upd_or_ins(ins_sql,(acc_info,student_id))
            if ret > 0:
                resp = '1'
            else: resp = '0'
        except Exception, e:
            import traceback
            e = traceback.format_exc()
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)


    @gen.coroutine
    def upd(self, acc_id):
        '''处理特殊事件'''
        resp = ''
        upd_sql = '''UPDATE tp_dorm_accident SET Fis_ok = 1,Fupd_time = UNIX_TIMESTAMP() WHERE Fid = %s'''
        try:
            ret = yield self.upd_or_ins(upd_sql,(acc_id,))
            if ret > 0:
                resp = '1'
            else: resp = '0'
        except Exception, e:
            import traceback
            e = traceback.format_exc()
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)


    @gen.coroutine
    def list(self, ok_type, start=0, offset=20):
        '''特殊事件列表'''
        resp = ''
        sel_sql = '''SELECT Fid,Faccident_info,Fstudent_id,Fis_ok,Fcreate_time FROM tp_dorm_accident'''
        param_list = []
        if ok_type == '0':#未处理
            sel_sql = sel_sql + ' WHERE Fis_ok = %s'
            param_list.append(0)
        elif ok_type == '1':#已处理
            sel_sql = sel_sql + ' WHERE Fis_ok = %s'
            param_list.append(1)

        sel_sql = sel_sql + ' LIMIT %s,%s'
        param_list.append(int(start))
        param_list.append(int(offset))
        try:
            ret = yield self.execute(sel_sql,tuple(param_list))
            resp = []
            for i in ret:
                resp.append({'id':i[0],'accInfo':i[1],'studentId':i[2],'isOk':i[3],'createTime':libtime.timestamp_2_datetime(i[4])})
        except Exception, e:
            import traceback
            e = traceback.format_exc()
            log.log_exception(self.__class__.__name__, e)
            resp = '-1'
        raise gen.Return(resp)